package com.xiaorong.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.commons.httpclient.util.DateUtil;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.xiaorong.Filter;
import com.xiaorong.Filter.Operator;
import com.xiaorong.Pageable;
import com.xiaorong.dao.AdminDao;
import com.xiaorong.dao.LogDao;
import com.xiaorong.dao.OrderDao;
import com.xiaorong.entity.Log;
import com.xiaorong.entity.Order;
import com.xiaorong.entity.vo.OrderVo;
import com.xiaorong.util.ClassRefUtil;
import com.xiaorong.util.DownloadUtils;
import com.xiaorong.util.ExcelUtils;

/**
 * 高风险订单管理
 * @author LV_FQ
 *
 */
@Controller
@RequestMapping("/order")
public class OrderController extends BaseController {
	
	@Resource
	private OrderDao orderDao;
	@Resource
	private LogDao logDao;
	@Resource
	private AdminDao adminDao;
	
	@RequestMapping("/edit.do")
	public String edit(Long id, HttpServletRequest request){
		String orderType = request.getParameter("orderType");
		if(id != null){
			Order order = orderDao.find(id);
			request.setAttribute("order", order);
			request.setAttribute("orderType", order.getOrderType());
		}else{
			request.setAttribute("orderType", orderType);
		}
		return "/order/edit";
	}
	
	@ResponseBody
	@RequestMapping(value="/update.do")
	public boolean update(@Valid Order order, Errors errors, HttpServletRequest request){
		Order entity = orderDao.find(order.getId());
		String admin = getCurrentAdmin(request);
		
		order.setSn(entity.getSn());
		order.setOrderType(entity.getOrderType());
		if(errors.hasErrors()){
			return false;
		}
		
		String changes = admin + "对订单"+entity.getSn()+"做了以下操作:<br>";
		Map<String, String> original = ClassRefUtil.getFieldValueMap(entity);
		Map<String, String> map = ClassRefUtil.getFieldValueMap(order);
		for (Map.Entry<String, String> entry : map.entrySet()) {
			String value = entry.getValue();
			String key = entry.getKey();
			
			if(StringUtils.isNotEmpty(value)){
				if(!value.equals(original.get(key))){
					changes += (key + ":  "+ original.get(key) +"-->"+ value +"<br>");
				}
			}else{
				if(StringUtils.isNotEmpty(original.get(key))){
					changes += (key + ":  "+ original.get(key) +"-->"+ value +"<br>");
				}
			}
			
		}
		
		orderDao.merge(order);
		
		
		changes = changes.replace("sn", "订单号").replace("reportDate", "报告日期")
		.replace("orderDate", "订单日期").replace("amount", "金额USD")
		.replace("cardNo", "卡号").replace("cardKeeper", "持卡人")
		.replace("passengerOne", "乘机人1").replace("passengerTwo", "乘机人2")
		.replace("ipCountry", "IP国家").replace("flightDate", "航班日期")
		.replace("voyage", "航程").replace("telphone", "联系电话").replace("email", "邮箱").replace("result", "处理结果")
		.replace("ticketNo", "票号").replace("remark", "备注")
		.replace("refuseResult", "telphone").replace("cardSpecies", "卡种").replace("buyerCountry", "购买者所在国家")
		.replace("attribute1", "拓展属性1").replace("attribute2", "拓展属性2").replace("attribute3", "拓展属性3")
		.replace("attribute4", "拓展属性4").replace("attribute5", "拓展属性5").replace("attribute6", "拓展属性6")
		.replace("attribute7", "拓展属性8").replace("attribute8", "拓展属性8").replace("attribute9", "拓展属性9");
		
		Log log = new Log();
		log.setOperation("修改订单补充说明");
		log.setOperator(admin);
		log.setContent(changes);
		log.setParameter("");
		log.setIp(request.getRemoteAddr());
		logDao.persist(log);
		
		return true;
	}
	
	@ResponseBody
	@Transactional
	@RequestMapping("/save.do")
	public boolean save(Order order, HttpServletRequest request){
		String orderType = request.getParameter("orderType");
		if(StringUtils.isBlank(orderType)){
			return false;
		}
		order.setOrderType(orderType);
		
		if(orderDao.isExistSn(order.getSn(), order.getOrderType() )){
			return false;
		}
		
		if(!validator.validate(order).isEmpty()){
			return false;
		}
		orderDao.persist(order);
		return true;
	}
	
	@ResponseBody
	@RequestMapping("/checkSn.do")
	public boolean checkSn(String sn, String orderType, HttpServletRequest request){
		if(StringUtils.isBlank(sn) || StringUtils.isBlank(orderType)){
			return false;
		}
		
		if(orderDao.isExistSn(sn, orderType)){
			return false;
		}
		return true;
	}
	
	@RequestMapping("/detail.do")
	public String detail(Long id, HttpServletRequest request){
		request.setAttribute("order", orderDao.find(id));
		return "/order/detail";
	}
	
	@RequestMapping("/list.do")
	public String list(OrderVo orderVo, Integer pageNumber, Integer pageSize, HttpServletRequest request){
		Pageable pageable = new Pageable(pageNumber, pageSize);
		
		List<Filter> filters = new ArrayList<Filter>();
		pageable.setFilters(filters);
		
		String orderType = request.getParameter("orderType");
		if(StringUtils.isNotBlank(orderType)){
			filters.add(new Filter("orderType", Operator.eq, orderType));
		}
		
		//使用反射做过滤条件
		Map<String, String> map = ClassRefUtil.getFieldValueMap(orderVo);
		for (Map.Entry<String, String> entry : map.entrySet()) {
			String value = entry.getValue();
			if(StringUtils.isNotEmpty(value)){
				if(entry.getKey().contains("Date1") || entry.getKey().contains("Date2")){
					if(entry.getKey().contains("Date1")){
						String key = entry.getKey().substring(0, entry.getKey().length()-1);
						if(StringUtils.isNotBlank(value)){
							filters.add(new Filter(key, Operator.between, value.trim(), DateUtil.formatDate(new Date(), "yyyy-MM-dd")));
						}
					}
					if(entry.getKey().contains("Date2")){
						String key = entry.getKey().substring(0, entry.getKey().length()-1);
						if(StringUtils.isNotBlank(value)){
							filters.add(new Filter(key, Operator.between, "1000-01-01", value.trim()));
						}
					}
					
				}else{
					if(StringUtils.isNotBlank(value)){
						filters.add(new Filter(entry.getKey(), Operator.like, "%"+value.trim()+"%"));
					}
				}
			}
		}
		request.setAttribute("orderVo", orderVo);
		request.setAttribute("orderType", orderType);
		request.setAttribute("page", orderDao.findPage(pageable));
		return "/order/list";
	}
	
	@ResponseBody
	@RequestMapping("/delete.do")
	public boolean delete(HttpServletRequest request,Long[] ids){
		if(!ArrayUtils.isEmpty(ids)){
			for(Long id : ids){
				orderDao.remove(id);
			}
		}
		return true;
	}

	/**
	 * 上传
	 * @param request
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
	@Transactional
	@RequestMapping(method=RequestMethod.POST,value="upload.do")
	public String upload(HttpServletRequest request,HttpServletResponse response, RedirectAttributes redirectAttributes){
		
		String orderType = request.getParameter("orderType");
		
		if(StringUtils.isBlank(orderType)){
			addFlashMessage(redirectAttributes,ERROR_TYPE, "导入失败，请先选中要导入的系统");
			return "redirect:list.do";
		}
		
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		MultipartFile multipartFile = multipartRequest.getFile("filedata");
		String sourceName = multipartFile.getOriginalFilename(); // 原始文件名
		String fileType = sourceName.substring(sourceName.lastIndexOf("."));

		System.out.println("上传的文件名为:"+sourceName+"类型为:"+fileType);

		String base = request.getSession().getServletContext().getRealPath("/")
				+ "attachments" + File.separator + "uploadedExcel";
		File file = new File(base);
		String path=base + File.separator + sourceName;
		if (!file.exists()) {
			file.mkdirs();
		}
		boolean isSuccess = true;
		String result = "";
		
		try{
			multipartFile.transferTo(new File(path));
			// 上传成功后读取Excel表格里面的数据
			Sheet sheet = ExcelUtils.readExcel(path);
			int lastRow = sheet.getLastRowNum();
			
			for(int i=1;i<=lastRow;i++){
				Order order = new Order();
				int y = 0;
				
				order.setReportDate(ExcelUtils.readValue(sheet, y++ , i));
				order.setOrderDate(ExcelUtils.readValue(sheet,y++,i));
				order.setSn(ExcelUtils.readValue(sheet,y++,i));
				order.setAmount(ExcelUtils.readValue(sheet,y++,i));
				order.setCardNo(ExcelUtils.readValue(sheet,y++,i));
				order.setCardKeeper(ExcelUtils.readValue(sheet,y++,i));
				
				order.setPassengerOne(ExcelUtils.readValue(sheet,y++,i));
				order.setPassengerTwo(ExcelUtils.readValue(sheet,y++,i));
				order.setIpCountry(ExcelUtils.readValue(sheet,y++,i));
				
				order.setFlightDate(ExcelUtils.readValue(sheet,y++,i));
				order.setVoyage(ExcelUtils.readValue(sheet,y++,i));
				order.setTelphone(ExcelUtils.readValue(sheet,y++,i));
				order.setEmail(ExcelUtils.readValue(sheet,y++,i));
				order.setResult(ExcelUtils.readValue(sheet,y++,i));
				order.setTicketNo(ExcelUtils.readValue(sheet,y++,i));
				order.setRemark(ExcelUtils.readValue(sheet,y++,i));
				order.setRefuseResult(ExcelUtils.readValue(sheet,y++,i));
				order.setCardSpecies(ExcelUtils.readValue(sheet,y++,i));
				order.setBuyerCountry(ExcelUtils.readValue(sheet,y++,i));
				
				//拓展属性
				order.setAttribute1(ExcelUtils.readValue(sheet,y++,i));
				order.setAttribute2(ExcelUtils.readValue(sheet,y++,i));
				order.setAttribute3(ExcelUtils.readValue(sheet,y++,i));
				order.setAttribute4(ExcelUtils.readValue(sheet,y++,i));
				order.setAttribute5(ExcelUtils.readValue(sheet,y++,i));
				order.setAttribute6(ExcelUtils.readValue(sheet,y++,i));
				order.setAttribute7(ExcelUtils.readValue(sheet,y++,i));
				order.setAttribute8(ExcelUtils.readValue(sheet,y++,i));
				order.setAttribute9(ExcelUtils.readValue(sheet,y++,i));
				
				if(orderDao.isExistSn(order.getSn(), orderType)){
					result += "第" + (i+1) + "行订单号重复！！\n";
					continue;
				}
				
				order.setOrderType(orderType);
				orderDao.persist(order);
			}
			
		}catch (Exception e) {
			e.printStackTrace();
			isSuccess = false;
		}finally{
			new File(path).delete();
		}
		
		Log log = new Log();
		log.setContent(result);
		log.setIp(request.getRemoteAddr());
		log.setOperation("导入风险订单");
		log.setOperator("系统提醒");
		log.setParameter(null);
		logDao.persist(log);
		
		if (isSuccess) {
			addFlashMessage(redirectAttributes,SUCCESS_TYPE, SUCCESS_MESSAGE);
		} else {
			addFlashMessage(redirectAttributes,ERROR_TYPE, "导入失败");
		}
		
		return "redirect:list.do";
	}
	
	/**
	 * 导出
	 * @param ids
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/download")
	public @ResponseBody  synchronized
	void download(Long[] ids, HttpServletRequest request, HttpServletResponse response) throws IOException {
		if (ids == null) {
			return;
		}
		List<Order> orders = orderDao.findList(ids);
		String[] head = {"报告日期","订单日期","订单号","金额USD","卡号","持卡人","乘机人1","乘机人2","IP国家",
				"航班日期","航程","联系电话","邮箱","处理结果","票号","备注","拒绝原因","卡种","购买人所在国家",
				"拓展属性1","拓展属性2","拓展属性3","拓展属性4","拓展属性5","拓展属性6","拓展属性7","拓展属性8","拓展属性9"};

		List<List<String>> datas = new ArrayList<List<String>>();
		
		for(Order order : orders){
			
			List<String> dataList = new ArrayList<String>();
			dataList.add(order.getReportDate());
			dataList.add(order.getOrderDate());
			dataList.add(order.getSn());
			dataList.add(order.getAmount());
			dataList.add(order.getCardNo());
			dataList.add(order.getCardKeeper());
			dataList.add(order.getPassengerOne());
			dataList.add(order.getPassengerTwo());
			dataList.add(order.getIpCountry());
			dataList.add(order.getFlightDate());
			dataList.add(order.getVoyage());
			dataList.add(order.getTelphone());
			dataList.add(order.getEmail());
			dataList.add(order.getResult());
			dataList.add(order.getTicketNo());
			dataList.add(order.getRemark());
			dataList.add(order.getRefuseResult());
			dataList.add(order.getCardSpecies());
			dataList.add(order.getBuyerCountry());
			
			//拓展属性
			dataList.add(order.getAttribute1());
			dataList.add(order.getAttribute2());
			dataList.add(order.getAttribute3());
			dataList.add(order.getAttribute4());
			dataList.add(order.getAttribute5());
			dataList.add(order.getAttribute6());
			dataList.add(order.getAttribute7());
			dataList.add(order.getAttribute8());
			dataList.add(order.getAttribute9());
			
			datas.add(dataList);
		}
		String location = request.getSession().getServletContext().getRealPath("") + "\\temp\\";
		String tempname = "ordertemp.xls";
		
        try {
        	HSSFWorkbook wb = ExcelUtils.exportExcel2FilePath(tempname, location, head, datas);
        	
        	if(wb != null){
        		DownloadUtils.download(tempname, "temp\\"+tempname, request, response);
        	}
        } catch (Exception e) {
        	e.printStackTrace();
        } finally {
        	
        }
	}

}
